package com.sx.water.modules.Controller;

import com.sx.water.modules.entity.IntegerTimeRainingBo;
import com.sx.water.modules.sever.SurfaceRainfallServer;
import com.sx.water.modules.sever.WaterRainServer;
import com.sx.water.util.CodeUtils;
import com.sx.water.util.DateUtils;
import com.sx.water.util.R;
import com.sx.water.util.TableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 首页
 * @description: 雨量接口
 * @author: taoxi
 * @create: 2018-11-05 10:14
 *
 **/
@RestController
@CrossOrigin
@RequestMapping(value = "/rain")
public class RainController {

    /**
     * 面雨量
     */
    @Autowired
    SurfaceRainfallServer surfaceRainfallServer;

    @Autowired
    WaterRainServer waterRainServer;




    public static IntegerTimeRainingBo getBo() {
        IntegerTimeRainingBo integerTimeRainingBo = new IntegerTimeRainingBo();
        integerTimeRainingBo.setProvince("浙江");
        integerTimeRainingBo.setCity("绍兴");
        integerTimeRainingBo.setCountry("");
        integerTimeRainingBo.setTown("");
        return integerTimeRainingBo;
    }


    /**
     * 面降水量 (基本信息)
     *
     * @param num  1/3/6/12/24
     * @param code 新政编码
     * @return
     */
    @CrossOrigin
    @RequestMapping("/surfaceRainfall")
    public R SurfaceRainfall(@RequestParam(value = "num") int num, @RequestParam(value = "code") String code) {
        // 默认 气象
        //获取最新时间 yymmddHH
        String time = surfaceRainfallServer.selectMaxtime();
        //获取乡镇name
        String country = CodeUtils.CodeNum.get(code);
        if(country==null){
            return R.error("无此行政编码:"+code);
        }
        IntegerTimeRainingBo integerTimeRainingBo = getBo();
        if (!(country.equals("绍兴"))) {
            integerTimeRainingBo.setCountry(country);

        }

        Map<String, String> map = TableUtil.getTimeComparison(num, time);
        integerTimeRainingBo.setStartTime(map.get("startTime"));
        integerTimeRainingBo.setEndTime(map.get("endTime"));
        integerTimeRainingBo.setDataBasesTimeParameter(map.get("tableSuffix"));
        //判断是否 时间间隔在同一张表
        if (map.get("tableSuffix2") != null) {
            //不是同一张表
            integerTimeRainingBo.setDataBasesTimeParameterBef(map.get("tableSuffix2"));
            StringBuffer stringBuffer = new StringBuffer();
            //动态语句  BETWEEN'18100100' and  '18103018'
            stringBuffer.append("BETWEEN").append(" ").append(map.get("startTime2")).append(" ").append("AND").append(" ").append(map.get("endTime2"));
            integerTimeRainingBo.setAutoStationAddSql(stringBuffer.toString());
        }
        List<Map<String, Object>> list = surfaceRainfallServer.selectSurfaceRainFall(integerTimeRainingBo);


        return R.ok().put("DS", list);
    }

    /**
     * 降水量信息
     *
     * @param code 新政编码
     * @param pr01/3/6/12/24 阀值 值
     * @return
     */
    @CrossOrigin
    @RequestMapping("/RainInfo")
    public R RainInfo(@RequestParam(value = "code") String code,@RequestParam(value = "pr01") String pr01,
                      @RequestParam(value = "pr03") String pr03,@RequestParam(value = "pr06") String pr06,@RequestParam(value = "pr12") String pr12,@RequestParam(value = "pr24") String pr24) {
        Map<String, Object> rainAll = new HashMap<String, Object>();
        //获取最新时间 yymmddHH
        String time = surfaceRainfallServer.selectMaxtime();

        //获取 站点数
        Map<String,Integer> mapNum= surfaceRainfallServer.selectGetCount();
       // String[] arry=type.split(",");
        int counts=mapNum.get("num1").intValue();


        //获取乡镇name
        String country =CodeUtils.CodeNum.get(code);
        if(country==null){
            return R.error("无此行政编码:"+code);
        }
        //阀值
        List<String> litPre = new ArrayList<>();
        litPre.add(0, pr01);
        litPre.add(1, pr03);
        litPre.add(2, pr06);
        litPre.add(3, pr12);
        litPre.add(4, pr24);

        Map<String, Object> mapPreAll = new HashMap<String, Object>();

        int[] nums = {1, 3, 6, 12, 24};
        for (int i = 0; i < nums.length; i++) {
            Map<String, Object> mapPre = new HashMap<String, Object>();
            IntegerTimeRainingBo integerTimeRainingBo = getBo();
            if (!(country.equals("绍兴"))) {
                integerTimeRainingBo.setCountry(country);
            }
            //设置阀值
            integerTimeRainingBo.setThresholdRain(litPre.get(i));
            Map<String, String> map = TableUtil.getTimeComparison(nums[i], time);
            integerTimeRainingBo.setStartTime(map.get("startTime"));
            integerTimeRainingBo.setEndTime(map.get("endTime"));
            integerTimeRainingBo.setDataBasesTimeParameter(map.get("tableSuffix"));
            //判断是否 时间间隔在同一张表
            if (map.get("tableSuffix2") != null) {
                //不是同一张表
                integerTimeRainingBo.setDataBasesTimeParameterBef(map.get("tableSuffix2"));
                StringBuffer stringBuffer = new StringBuffer();
                //动态语句  BETWEEN'18100100' and  '18103018'
                stringBuffer.append(" ").append("BETWEEN").append(" ").append(map.get("startTime2")).append(" ").append("AND").append(" ").append(map.get("endTime2"));
                integerTimeRainingBo.setAutoStationAddSql(stringBuffer.toString());
            }
            //降水统计时段 所有站点
            List<Map<String, Object>> listpre = surfaceRainfallServer.selectGetRainInfo(integerTimeRainingBo);
            //降水统计时段 站点 超过阀值
            List<Map<String, Object>> listpre2 = surfaceRainfallServer.selectGetRainInfo2(integerTimeRainingBo);
            for(int m=0;m<listpre.size();m++){
               listpre.get(m).put("tyCh","1");
            }
            for(int m=0;m<listpre2.size();m++){
                listpre2.get(m).put("tyCh","1");
            }
            mapPre.put("count", listpre2.size());
            mapPre.put("stationAll", listpre);
            mapPre.put("stationFull", listpre2);
            mapPreAll.put(nums[i]+"",mapPre);
        }
        rainAll.put("count",counts);
        Date date= DateUtils.stringToDate(time,DateUtils.DATE_TIME_PATTERN_1);

        rainAll.put("time",DateUtils.format(date,DateUtils.DATE_TIME_PATTERN_4));
        rainAll.put("rain",mapPreAll);

        return R.ok().put("DS", rainAll);
    }

    //近12小时逐小时最大雨强
    @CrossOrigin
    @RequestMapping("/RainStrong")
    public R RainStrong(@RequestParam(value = "code") String code) {
        Map<String, Object> listResult =new HashMap<>();

        //获取最新时间 yymmddHH
        String time = surfaceRainfallServer.selectMaxtime();
        //获取乡镇name
        String country =CodeUtils.CodeNum.get(code);
        if(country==null){
            return R.error("无此行政编码:"+code);
        }
        IntegerTimeRainingBo integerTimeRainingBo = getBo();
        if (!(country.equals("绍兴"))) {
            integerTimeRainingBo.setCountry(country);
        }

        Map<String, String> map = TableUtil.getTimeComparison(12, time);
        integerTimeRainingBo.setStartTime(map.get("startTime"));
        integerTimeRainingBo.setEndTime(map.get("endTime"));
        integerTimeRainingBo.setDataBasesTimeParameter(map.get("tableSuffix"));
        //判断是否 时间间隔在同一张表
        if (map.get("tableSuffix2") != null) {
            //不是同一张表
            integerTimeRainingBo.setDataBasesTimeParameterBef(map.get("tableSuffix2"));
            StringBuffer stringBuffer = new StringBuffer();
            //动态语句  BETWEEN'18100100' and  '18103018'
            stringBuffer.append("BETWEEN").append(" ").append(map.get("startTime2")).append(" ").append("AND").append(" ").append(map.get("endTime2"));
            integerTimeRainingBo.setAutoStationAddSql(stringBuffer.toString());
        }
        Map<String,List<Map<String, Object>>> stringObjectMap=surfaceRainfallServer.selectRainStrong(integerTimeRainingBo);

        listResult.put("hour",stringObjectMap.get("hour"));
        listResult.put("minit",stringObjectMap.get("minit"));

        return R.ok().put("DS", listResult);
    }


    /**
     * @param code 行政编码
     * @param number 12 /24
     * @param starTime yymmddHH
     * @param endTime yymmddHH
     * @return
     */
    //县面雨量逐小时
    @CrossOrigin
    @RequestMapping("/FaceRainFallByContry")
    public R FaceRainFallByHour(@RequestParam(value = "code") String code,String number,String starTime,String endTime) {

        Map<String, Object> listResult =new HashMap<>();
        Map<String, String> map =new HashMap<>();
        int num;
        String time = surfaceRainfallServer.selectMaxtime();
        //获取最新时间 yymmddHH
        if(number!=null && number!=""){
            //time = surfaceRainfallServer.selectMaxtime();
            map = TableUtil.getTimeComparison(Integer.parseInt(number), time);
            num=1;
        }else {
            num=2;
            //计算时间差 （小时数）
            DateFormat df = new SimpleDateFormat("yyMMddHH");
            try {
                Date d1 = df.parse("endTime");
                Date d2 = df.parse("starTime");
                int hour=(int)((d1.getTime() - d2.getTime())/(60*60*1000));
                map = TableUtil.getTimeComparison(hour, endTime);

            } catch (ParseException e) {
                System.out.println(e.getMessage());
            }
        }
        //获取乡镇name
        String country =CodeUtils.CodeNum.get(code);
        if(country==null){
            return R.error("无此行政编码:"+code);
        }
        IntegerTimeRainingBo integerTimeRainingBo = getBo();
        if (!(country.equals("绍兴"))) {
            integerTimeRainingBo.setCountry(country);
        }

        integerTimeRainingBo.setStartTime(map.get("startTime"));
        integerTimeRainingBo.setEndTime(map.get("endTime"));
        integerTimeRainingBo.setDataBasesTimeParameter(map.get("tableSuffix"));
        //判断是否 时间间隔在同一张表
        if (map.get("tableSuffix2") != null) {
            //不是同一张表
            integerTimeRainingBo.setDataBasesTimeParameterBef(map.get("tableSuffix2"));
            StringBuffer stringBuffer = new StringBuffer();
            //动态语句  BETWEEN'18100100' and  '18103018'
            stringBuffer.append("BETWEEN").append(" ").append(map.get("startTime2")).append(" ").append("AND").append(" ").append(map.get("endTime2"));
            integerTimeRainingBo.setAutoStationAddSql(stringBuffer.toString());
        }
        Map<String, List<Map<String, Object>>> stringListMap=surfaceRainfallServer.selectFaceRainByCountry(integerTimeRainingBo,num);
        List<Map<String, Object>> contryByHour = stringListMap.get("hour");
        List<Map<String, Object>> contryByMint = stringListMap.get("mint");
        for(int m=0;m<contryByHour.size();m++){
            contryByHour.get(m).put("tyCh","1");
        }
        for(int m=0;m<contryByMint.size();m++){
            contryByMint.get(m).put("tyCh","1");
        }
        listResult.put("hour",contryByHour);
        listResult.put("minit",contryByMint);

        return R.ok().put("DS", listResult);
    }


    /**
     * @param code  站点id
     * @param number 12/24
     * @param starTime yymmddHH
     * @param endTime yymmddHH
     * @return
     */
    //站点 逐小时 面雨量
    @CrossOrigin
    @RequestMapping("/FaceRainFallByStation")
    public R FaceRainFallByStation(@RequestParam(value = "code") String code,String number,String starTime,String endTime) {

        Map<String, Object> listResult =new HashMap<>();
        Map<String, String> map =new HashMap<>();
        int num;
        String time = surfaceRainfallServer.selectMaxtime();
        //获取最新时间 yymmddHH
        if(number!=null && number!=""){
            //time = surfaceRainfallServer.selectMaxtime();
            map = TableUtil.getTimeComparison(Integer.parseInt(number), time);
            num=1;
        }else {
            num=2;
            //计算时间差 （小时数）
            DateFormat df = new SimpleDateFormat("yyMMddHH");
            try {
                Date d1 = df.parse("endTime");
                Date d2 = df.parse("starTime");
                int hour=(int)((d1.getTime() - d2.getTime())/(60*60*1000));
                map = TableUtil.getTimeComparison(hour, endTime);

            } catch (ParseException e) {
                System.out.println(e.getMessage());
            }
        }

        IntegerTimeRainingBo integerTimeRainingBo = getBo();
        integerTimeRainingBo.setStationId(code);
        integerTimeRainingBo.setStartTime(map.get("startTime"));
        integerTimeRainingBo.setEndTime(map.get("endTime"));
        integerTimeRainingBo.setDataBasesTimeParameter(map.get("tableSuffix"));
        //判断是否 时间间隔在同一张表
        if (map.get("tableSuffix2") != null) {
            //不是同一张表
            integerTimeRainingBo.setDataBasesTimeParameterBef(map.get("tableSuffix2"));
            StringBuffer stringBuffer = new StringBuffer();
            //动态语句  BETWEEN'18100100' and  '18103018'
            stringBuffer.append("BETWEEN").append(" ").append(map.get("startTime2")).append(" ").append("AND").append(" ").append(map.get("endTime2"));
            integerTimeRainingBo.setAutoStationAddSql(stringBuffer.toString());
        }
        Map<String, List<Map<String, Object>>> stringListMap=surfaceRainfallServer.selectFaceRainByStation(integerTimeRainingBo,num);
        List<Map<String, Object>> contryByHour = stringListMap.get("hour");
        List<Map<String, Object>> contryByMint = stringListMap.get("mint");
        for(int m=0;m<contryByHour.size();m++){
            contryByHour.get(m).put("tyCh","1");
        }
        for(int m=0;m<contryByMint.size();m++){
            contryByMint.get(m).put("tyCh","1");
        }

        listResult.put("hour",contryByHour);
        listResult.put("minit",contryByMint);

        return R.ok().put("DS", listResult);
    }


    public static String getTimeWord(String str, int num) {
        DecimalFormat df = new DecimalFormat("00");
        int result = Integer.parseInt(str) - num;
        if (result >= 0) {
            return df.format(result);
        } else {
            return df.format((24 + result));
        }

    }

    public static int getTimeWord2(String str, int num) {
        int result = Integer.parseInt(str) - num;
        if (result >= 0) {
            return result;
        } else {
            return (24 + result);
        }

    }



    /**
     * @return  站点 的信息
     */
    @CrossOrigin
    @RequestMapping("/RainBysTationInfo")
    public R RainBysTationInfo(){
        List<Map<String,Object>> list=surfaceRainfallServer.selectRainStationInfo();
        if(!list.isEmpty() && list.size()>0) {
            for(int i=0 ;i<list.size();i++){
                Float lon=Float.parseFloat(list.get(i).get("lon").toString());
                list.get(i).put("lon",lon/100);
                Float lat=Float.parseFloat(list.get(i).get("lat").toString());
                list.get(i).put("lat",lat/100);
                list.get(i).put("codes", CodeUtils.CodeName.get((String)list.get(i).get("town")));
                list.get(i).put("tyCh","1");
            }
        }
        return R.ok().put("DS", list);
    }


}
